<?php


namespace frontend\themes\basic\_widgets;

use Yii;
use yii\bootstrap\Html;
use yii\db\Query;
use yii\bootstrap\Nav;
use yii\bootstrap\Widget;

class LanguageSwitcherWidget extends Widget
{
    public $table = '{{%languages}}';
    private $_languages;

    public function init()
    {
        parent::init();
        $this->_languages = (new Query())->from($this->table)->where(['published' => 1])->orderBy('ordering')->all();
    }

    public function run()
    {
        $languageItems = [];
        $currentLanguage = [];
        foreach ($this->_languages as $language) {
            $languageItems[] = [
                'label' => $language['title_native'],
                'url' => ['/site/language'],
                'linkOptions' => [
                    'data' => [
                        'method' => 'post',
                        'params' => ['lang' => $language['code']]
                    ]
                ]
            ];
            if (Yii::$app->language === $language['code']){
                $currentLanguage = $language;
            }
        }
        return Nav::widget([
            'options' => ['class' => 'navbar-nav navbar-right'],
            'encodeLabels' => false,
            'items' => [
                [
                    'label' => Html::icon('globe').' '.$currentLanguage['title_native'],
                    'items' => $languageItems
                ]
            ]
        ]);
    }
}